﻿using Common.Logging;
using Infrastructure.Lib.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CJPictureMove.Job
{
    public class FolderDeamon
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(FolderDeamon));

        private Configuration _config { get; set; }

        private FileSystemWatcher watcher = new FileSystemWatcher();

        private FolderDeamon()
        {
            var xmlPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "PictureMove.xml");
            _config = SerializeHelper.FromXmlFile<Configuration>(xmlPath);

            if (!FileHelper.IsExistDirectory(_config.To))
            {
                FileHelper.CreateDirectory(_config.To);
            }

            watcher.Path = _config.From;
            //监控遍历子目录
            watcher.IncludeSubdirectories = true;
            watcher.InternalBufferSize = 65536;
            watcher.Filter = "*.jpg";
            watcher.Created += new FileSystemEventHandler(OnCreatedMoveOriginDeleteThumb);
            watcher.EnableRaisingEvents = true;
        }

        private void OnCreatedMoveOriginDeleteThumb(object source, FileSystemEventArgs e)
        {
            try
            {
                //判断路径里是否包含监测的站点
                var query = from s in _config.Sites
                            where e.FullPath.ToLower().Contains(s.Id.ToLower())
                            select s;

                if (query.Count() == 0) return;

                if (!FileHelper.IsFileReady(e.FullPath)) return;

                //删除缩略图
                if (e.FullPath.ToLower().Contains("thumb"))
                {
                    FileHelper.Delete(e.FullPath);
                    return;
                }

                //移动文件
                FileInfo fi = new FileInfo(e.FullPath);
                var lastWriteTime = fi.LastWriteTime;
                var toFolder = Path.Combine(_config.To, query.ToList()[0].Id, lastWriteTime.ToString(@"yyyy\\MM\\dd"));
                //var toFile = Path.Combine(toFolder, fi.Name);
                if (!FileHelper.IsExistDirectory(toFolder))
                {
                    FileHelper.CreateDirectory(toFolder);
                }
                FileHelper.Move(e.FullPath, toFolder);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
        }

        public void Watch()
        {

        }

        public static FolderDeamon Instance
        {
            get
            {
                return FolderDeamonInstance.instance;
            }
        }

        class FolderDeamonInstance
        {
            internal static readonly FolderDeamon instance = new FolderDeamon();
            static FolderDeamonInstance() { }
        }

    }
}
